import java.util.*;
import java.util.Map.Entry;


public class TreeMapDemo
{
	public static void main(String[] args)
	{
		TreeMap<Student, String> hm = new TreeMap<Student, String>(
				new Comparator<Student>()
				{
					public int compare(Student st1, Student st2)
					{
						if (st1.getAge() > st2.getAge())
							return 1;
						else if (st1.getAge() == st2.getAge())
							return st1.getName().compareTo(st2.getName());
						return -1;
					}
				});

		hm.put(new Student("张三", 20), "北京");
		hm.put(new Student("李四", 21), "西安");
		hm.put(new Student("王五", 15), "重庆");
		hm.put(new Student("赵六", 26), "成都");
		hm.put(new Student("孙悦", 25), null);   //HashMap可以存null值，而HashTable不可以，因此，不能用get方法返回null来判断键值是否存在，而应该用containsKey方法判断.
		//注意：put方法有返回值，返回的是键值对应关系的值，集合中原来对键值没有指定关系，返回null，有则返回原来的值.
		String a = hm.put(new Student("小七", 12), "绵阳");   //原来集合中没有对键值(new Student("小七", 12))指定关系，返回为null
		//hm.put(new Student("小七", 12), "绵阳"); //未覆盖hashCode方法和equals方法时，能够存入相同的元素.
		String b = hm.put(new Student("小七", 12), "太原"); //原来对该键值(new Student("小七", 12))指定了对应关系，返回原来已经指定的值.而这里的太原覆盖了原来的绵阳.
		System.out.println(a + ".." + b);
		Set <Map.Entry<Student, String>> s = hm.entrySet();
		for (Iterator<Map.Entry<Student, String>> it = s.iterator(); it.hasNext(); )
		{
			Map.Entry<Student, String> me = it.next();
			Student stu = me.getKey();
			String addr = me.getValue();
			System.out.println(stu.getName() + ".." + stu.getAge() + ".." + addr);
		}
		Student keyFlag = hm.firstEntry().getKey();
		for (int i = 0; i < 30; i ++) {
			keyFlag = nextChannel(hm, keyFlag);
			System.out.println(keyFlag.getName() + ".." + keyFlag.getAge());
		}
	}
	
	private static Student nextChannel(TreeMap<Student, String> map, Student keyFlag) {
		if (map.isEmpty()) {
			return null;
		}
		try {
			Entry<Student, String> entry = map.higherEntry(keyFlag);
			if (entry == null) {
				entry = map.firstEntry();
			}
			if (entry != null) {
				keyFlag = entry.getKey();
				return keyFlag;
			}
		} finally {
		}
		return null;
	}
}
class Student
{
	private String name;
	private int age;
	Student(String name, int age)
	{
		this.name = name;
		this.age  = age;
	}
	public String getName()
	{
		return name;
	}
	public int getAge()
	{
		return age;
	}
	public int hashCode()  //注意，判断HashSet、HashMap集合的唯一性，覆盖hashCode和equals方法，而TreeMap、TreeMap排序实现comparable或comparator接口.
	{
		return name.hashCode() + age*29;
	}
	public boolean equals(Object obj)
	{
		if (!(obj instanceof Student))
			return false;
		Student student = (Student)obj;
		return this.name.equals(student.name) && this.age == student.age;  
	}
	public String toString()
	{
		return name + ".." + age;
	}
}